package redis;

import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;

import java.util.Collections;
import java.util.UUID;

/**
 * Created by Zhou_Bing on 2019/10/15.
 */
public class RedisUtil {

    private static final String clientId = UUID.randomUUID().toString().replaceAll("-","");
    private static final String RELEASE_LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    /**
     * 加锁 (锁的value为clientId)
     * @param lockKey 锁的key
     * @param seconds 锁的过期时间（秒,EX 单位为秒 PX单位为毫秒）
     * @return
     */
    public static Boolean lock(String lockKey, long seconds, RedisTemplate<String,String> redisTemplate){
        return redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
            Jedis jedis = (Jedis) redisConnection.getNativeConnection();
            String result = jedis.set(lockKey,clientId,"NX","EX",seconds);
            if("OK".equals(result)){
                return Boolean.TRUE;
            }else{
                return Boolean.FALSE;
            }
        });
    }

    /**
     * 解锁（只解value为clientId的锁）
     * @param lockKey
     * @param redisTemplate
     * @return
     */
    public static Boolean unLock(String lockKey,RedisTemplate<String,String> redisTemplate){
        return redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
            Jedis jedis = (Jedis) redisConnection.getNativeConnection();
            Object result = jedis.eval(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey),
                    Collections.singletonList(clientId));
            if("OK".equals(result)){
                return Boolean.TRUE;
            }else{
                return Boolean.FALSE;
            }
        });
    }
}
